<template>
  <div class="home">
    <van-search
      v-model="keyword"
      show-action
      placeholder="请输入搜索关键词"
      @search="onSearch"
    >
      <template #action>
        <div @click="onSearch">搜索</div>
      </template>
    </van-search>

    <h2>历史记录</h2>
    <van-button @click="clear">清空</van-button>
    <ul>
      <li v-for="(item, index) in history" :key="index">
        {{ item }} <span @click="del(index)">x</span>
      </li>
    </ul>
  </div>
</template>

<script>
import { Dialog } from "vant";
export default {
  data() {
    return {
      keyword: "",
      //搜索关键子
      history: [],
      //历史记录
    };
  },
  mounted() {
    if (localStorage.getItem("history")) {
      this.history = JSON.parse(localStorage.getItem("history"));
    }
    console.log(this.history);
  },
  methods: {
    onSearch() {
      if (this.history.length < 3) {
        this.history.unshift(this.keyword);
      } else {
        this.history.pop();
        this.history.unshift(this.keyword);

        //为了保证三条历史记录是最新的三条 删除尾部的最后一条 并往开头添加一条
      }
      // this.$router.push({ path: "/list", query: { keyword: this.keyword } });
      //先跳转再watch  vue的视图会等到这里面所有的同步代码执行完之后才会更新

      // setTimeout(() => {
      //   this.$router.push({ path: "/list", query: { keyword: this.keyword } });
      // }, 0);
      //把跳转变成异步的代码 这样就会在watch之后才执行这个 跳转
      // 还可以用vue中nexttick解决这个问题

      this.$nextTick(() => {
        this.$router.push({ path: "/list", query: { keyword: this.keyword } });
      });

      //在dom更新之后执行的延迟回调  也是把同步的代码变成异步的代码

      //在搜索事件里除了保存历史记录外，还需要跳转页面 并且把搜索关键字传到搜索结果页面
    },
    del(index) {
      this.history.splice(index, 1);
    },
    clear() {
      Dialog.confirm({
        title: "标题",
        message: "是否删除",
      })
        .then(() => {
          this.history = [];
        })
        .catch(() => {
          // on cancel
        });
    },
  },
  watch: {
    history: {
      handler(newval) {
        console.log(newval);
        localStorage.setItem("history", JSON.stringify(newval));
      },
      deep: true,
    },
  },
};
</script>
